<script setup lang="ts">
import MdPreview from '@/components/markdown/MdPreview.vue'
import CheckBox from '@/views/agent/chat/components/CheckBox.vue'
import CollectForm from '@/views/agent/chat/components/CollectForm.vue'
import OpeningRemarks from '@/views/agent/chat/components/OpeningRemarks.vue'
import StepLoading from '@/views/agent/chat/components/StepLoading.vue'
import * as echarts from 'echarts'
import { cloneDeep } from 'lodash'
import { computed, nextTick, ref } from 'vue'
import { barAgent, industryAgent, IndustryResearchProcessLoading, pieAgent, CONTENT_REGEXP } from './data'
import applicationApi from '@/api/application'

const types = ['行业发展政策分析', '行业产业链分析', '行业环境分析', '行业竞争分析', '行业技术演进分析']
const tip = 'AI行业研究报告'
const formConfig = [
  {
    title: '输入行业',
    slotName: 'one'
  },
  {
    title: '选择分析维度',
    slotName: 'two'
  },
]

const props = withDefaults(
  defineProps<{
    appId?: any
    chatId?: string
    applicationDetails: any
  }>(),
  {
  }
)
const step = ref(0)
const loading = ref(false)
const topTips = ref(tip)


const formData: any = ref({})
const setFormDataChecked = (val: any) => {
  formData.value.checked = val
}

function onBack () {
  step.value = 0;
  formData.value.checked = [];
  formData.value.industry = [];
}

const hasSubmit = computed(() => {
  return formData.value.industry && (formData.value.checked || []).length > 0 && !loading.value
})

async function onSubmit () {
  step.value = 1;
  loading.value = true;
  const allTasks: any = []
  types.forEach((v: string, i: number) => {
    if (formData.value.checked.includes(v)) {
      console.log(i)
      allTasks.push(getOneResult(i, 'result' + i));
    }
  })
  try {
    await Promise.all(allTasks);
    /*await nextTick(() => {
      setTimeout(() => {
        pieRender();
        barRender();
      }, 300)
    })*/
    // 处理所有请求的结果
    // 可以根据需要将结果保存到某个状态或进行其他操作
  } catch (error) {
    console.error('Error occurred during tasks execution:', error);
    // 处理错误情况
  } finally {
    loading.value = false;
  }
}


const resultContent: any = ref({
  result1: "",
  result0: "",
  result3: "",
  result2: "",
  result4: ""
})

/**
 * 获取任务
 * @param index
 * @param key
 */
async function getOneResult (index: number, key: string) {
  const { appId, apiKey }: any = industryAgent[index]
  const chatData = await applicationApi.getChatOtherOpen(appId, apiKey)
  const data = await applicationApi.postChatMessageNew(chatData?.data, { stream: false, message: formData.value.industry, apiKey })
  resultContent.value[key] = data.data.content;
}

async function pieRender() {
  const { appId, apiKey } = pieAgent
  const chatData = await applicationApi.getChatOtherOpen(appId, apiKey)
  const data = await applicationApi.postChatMessageNew(chatData?.data, { stream: false, message: '数据', apiKey })
  console.log('pieRender', data)
  const pieData = JSON.parse(cloneDeep(data.data.content.replaceAll(CONTENT_REGEXP, '')))
  console.log('pieRender',pieData)
  const total = pieData.data.reduce((total: number, obj: any) => +total + +obj.value, 0)
  console.log('pieRender', total)
  const pieDom: any = document.querySelector('.pieRef')
  const myChart = echarts.init(pieDom);
  const option = {
    title: {
      text: pieData.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    graphic: {
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: `总计\n${total}`, // 中间显示的文本，可以换行
        textAlign: 'center',
        fontSize: '16px'
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: false,
          position: 'center'
        },
        data: pieData.data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]

  };
  myChart.setOption(option);
}

async function barRender () {
  const { appId, apiKey } = barAgent
  const chatData = await applicationApi.getChatOtherOpen(appId, apiKey)
  const data = await applicationApi.postChatMessageNew(chatData?.data, { stream: false, message: '数据', apiKey })
  console.log('barRender', data)
  const barData = JSON.parse(cloneDeep(data.data.content.replaceAll(CONTENT_REGEXP, '')))
  console.log('barRender',barData)
  const barDom: any = document.querySelector('.barRef')
  const myChart = echarts.init(barDom);
  const option = {
    title: {
      text: barData.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: barData.data.map((v: any) => v.name),
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '60%',
        data: barData.data.map((v: any) => v.value),
      }
    ]

  };
  myChart.setOption(option);
}

const active = computed(() => {
  if (formData.value.industry && (formData.value.checked || []).length === 0) {
    return 1
  }
  if (formData.value.industry && (formData.value.checked || []).length > 0) {
    return 2
  }
  return 0
})
</script>

<template>
  <OpeningRemarks class="mb-12" :title="props.applicationDetails.name" :description="props.applicationDetails.desc"  :avatar="props.applicationDetails.avatar"/>
  <el-card class="mt-12 mb-12" shadow="never" v-if="step !== 1">
    <div class="ai-start">
      <div class="ai-start-tips">
        <el-icon @click="onBack" v-if="step === 1"><ArrowLeftBold /></el-icon>
        <div class="ai-start-tips-ellipsis">
          {{ topTips }}
        </div>
      </div>
      <el-button type="primary" size="small" @click="onSubmit" :disabled="!hasSubmit">开始分析</el-button>
    </div>
  </el-card>
  <CollectForm v-if="step === 0" :data="formConfig" :active="active">
    <template #one>
      <el-input v-model="formData.industry" placeholder="请输入" />
    </template>
    <template #two>
      <CheckBox :data="types" @update="setFormDataChecked" :show-check-box="true"/>
    </template>
  </CollectForm>
  <StepLoading v-if="step === 1" :data="IndustryResearchProcessLoading" :loading="loading" :applicationDetails="props.applicationDetails">
    <el-card v-if="resultContent.result0" body-style="padding: 20px 30px;">
      <el-row>
        <el-col :span="24">
          <MdPreview
            editorId="preview-only"
            :modelValue="resultContent.result0"
            class="maxkb-md"
          />
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-12" v-if="resultContent.result1" body-style="padding: 20px 30px;">
      <el-row>
<!--        <el-col :span="24">
          <div class="pieRef" style="height: 300px"></div>
        </el-col>-->
        <el-col :span="24">
          <MdPreview
            editorId="preview-only"
            :modelValue="resultContent.result1"
            class="maxkb-md"
          />
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-12" v-if="resultContent.result2" body-style="padding: 20px 30px;">
      <el-row>
<!--        <el-col :span="24">
          <div class="barRef" style="height: 300px"></div>
        </el-col>-->
        <el-col :span="24">
          <MdPreview
            editorId="preview-only"
            :modelValue="resultContent.result2"
            class="maxkb-md"
          />
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-12" v-if="resultContent.result3" body-style="padding: 20px 30px;">
      <el-row>
        <el-col :span="24">
          <MdPreview
            editorId="preview-only"
            :modelValue="resultContent.result3"
            class="maxkb-md"
          />
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-12" v-if="resultContent.result4" body-style="padding: 20px 30px;">
      <el-row>
        <el-col :span="24">
          <MdPreview
            editorId="preview-only"
            :modelValue="resultContent.result4"
            class="maxkb-md"
          />
        </el-col>
      </el-row>
    </el-card>
  </StepLoading>
</template>

<style scoped lang="scss">

</style>
